package com.liuzy;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 服务监听端口等待客户端连接
 * 
 * @author liuzy
 * @version 2015年5月1日
 */
public class Server {
	
	private static ServerSocket server = null;
	
	private static int port = 8189;
	
	private static boolean isRun = true;
	
	private static Map<String, Task> taskMap = new HashMap<>();
	
	private static int id = 0;
	
	private Server() {
		
	}
	
	public static void startup() {
		startup(port);
	}
	
	public static void startup(int port) {
		Server.port = port;
		try {
			server = new ServerSocket(port);
			System.out.println("已启动监听,端口 " + port + "!");
			Socket socket = null;
			Task task = null;
			while (isRun) {
				socket = server.accept();
				++id;
				task = new Task(socket, id);
				taskMap.put("task"+id, task);
				task.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void shutdown() {
		isRun = false;
		for (String key : taskMap.keySet()) {
			Task task = taskMap.get(key);
			task.stopTask();
		}
		try {
			// 用此办法让Server停止等待accept
			new Socket("localhost", port).shutdownOutput();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void stopTask(int id) {
		Task task = taskMap.get("task" + id);
		task.stopTask();
		removeTask(id);
	}
	
	public static void removeTask(int id) {
		taskMap.remove("task" + id);
	}
	
	public static String getStatus() {
		StringBuffer sb = new StringBuffer();
		sb.append("**************\r\n已连接客户端数量 ").append(taskMap.size())
		.append("\r\n").append(taskMap.toString()).append("\r\n**************\r\n");
		return sb.toString();
	}
	
}
